import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_train.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/page/train/approve/train_approve_item_widget.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/14.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class TrainApproveItemPage extends StatefulWidget {
  final int pageFlag;

  TrainApproveItemPage(this.pageFlag);

  @override
  State<StatefulWidget> createState() {
    return _TrainItemPageState();
  }
}

class _TrainItemPageState extends State<TrainApproveItemPage>
    with AutomaticKeepAliveClientMixin {
  //标签页面保活 或者称保持状态
  @override
  bool get wantKeepAlive => true;

  StreamController<int> _streamController = StreamController.broadcast();

  @override
  void initState() {
    super.initState();
    print("页面创建 ${widget.pageFlag}");
    getMyTrainListFunction();
    _streamController.stream.listen((event) {
      getMyTrainListFunction();
    });
  }

  @override
  void dispose() {
    _streamController.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    if (_isLoading) {
      return LoadingWidget();
    }
    if (_list == null || _list.length == 0) {
      return NoDataWidget(
        clickCallBack: () async {
          setState(() {
            _isLoading = true;
          });
          await getMyTrainListFunction();
          ToastUtils.showToast("已刷新");
        },
      );
    }

    //一个列表 切记不要再使用 Scaffold
    //否则会拦截事件 失去滑动联动效果
    return RefreshIndicator(
      //下拉刷新回调方法
      onRefresh: () async {
        //模拟网络刷新 等待2秒
        await getMyTrainListFunction();
        //返回值以结束刷新
        return Future.value(true);
      },
      child: ListView.builder(
        //去除内边距
        padding: EdgeInsets.all(0),
        //列表子Item个数
        itemCount: _list.length,
        //每个子Item的布局构建
        itemBuilder: (BuildContext context, int index) {
          TrainApproveBean approveBean = _list[index];
          return TrainApproveItemWidget(approveBean, index, _streamController);
        },
      ),
    );
  }

  CancelToken _cancelToken;
  bool _isLoading = true;
  List<TrainApproveBean> _list = [];

  Future<bool> getMyTrainListFunction() async {
    Map<String, dynamic> monthMap = {
      "statues": widget.pageFlag,
    };
    if (_cancelToken != null && !_cancelToken.isCancelled) {
      _cancelToken.cancel();
    }
    _cancelToken = new CancelToken();
    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.trainApproveList,
      queryParameters: monthMap,
      cancelTag: _cancelToken,
    );

    if (statisRresponseInfo.success) {
      List responseData = statisRresponseInfo.data["list"];
      if (responseData != null) {
        _list.clear();
        responseData.forEach((element) {
          _list.add(TrainApproveBean.fromJson(element));
        });
      }
    }
    _isLoading = false;

    if (mounted) {
      setState(() {});
    }

    return Future.value(true);
  }
}
